$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'freightages/freighttemplate/list',
        datatype: "json",
        colModel: [
            {label: 'templateId', name: 'templateId', index: 'template_id', width: 50, key: true,hidden:true,align:'center' },
            {label: '模板名称', name: 'templateName', index: 'template_name', width: 80,align:'center',
                formatter:function(value, options, row) {
                    var actions = [];
                    actions.push('<a href="javascript:void(0);" onclick="return info(' + row.templateId + ');">' + row.templateName + '</a>');
                    return actions.join(' ');
                }
             },
            {
                label: '模板类型', name: 'templateType', index: 'template_type', width: 80,align:'center',
                formatter: function (value, options, row) {
                    if (value == 'shop') {
                        return '店铺';
                    } else if (value == 'sku') {
                        return '单品';
                        return '';
                    }
                }
            },
            {
                label: '满件包邮：', name: 'freeShipping', index: 'free_shipping', width: 80,align:'center',
                formatter: function (value, options, row) {
                    if (value == '0') {
                        return '不包邮';
                    } else if (value == '1') {
                        return '包邮';
                    }
                    return '';
                }
            },
            {
                label: '计价规则', name: 'valuationWay', index: 'valuation_way', width: 80,align:'center',
                formatter: function (value, options, row) {
                    if (value == 'weight') {
                        return '按重量';
                    } else if (value == 'unit') {
                        return '按件';
                    }
                    return '';
                }
            },
            {label: '首重(首件)', name: 'firstUnit', index: 'first_unit', width: 80,align:'center'},
            {label: '首重费用(元)', name: 'firstPrice', index: 'first_price', width: 80,align:'center'},
            {label: '续重(续件)', name: 'continueUnit', index: 'continue_unit', width: 80,align:'center'},
            {label: '续重(续件)费用', name: 'continuePrice', index: 'continue_price', width: 80,align:'center'},
            {
                label: '是否默认模板:', name: 'defTemplate', index: 'def_template', width: 80,align:'center',
                formatter: function (value, options, row) {
                    if (value == '0') {
                        return '非默认模板';
                    } else if (value == '1') {
                        return '默认模板';
                    }
                    return '';
                }
            },
            {
                label: '是否失效:', name: 'disabled', index: 'disabled', width: 80,hidden:true,align:'center',
                formatter: function (value, options, row) {
                    if (value == '0') {
                        return '不失效';
                    } else if (value == '1') {
                        return '失效';
                    }
                    return '';
                }
            },
            { label: '关联供应商ID', name: 'supplierId', index: 'supplier_id', width: 80,hidden:true },
            {
                label: 'type', name: 'providerType', index: 'provider_type', width: 80,align:'center',
                formatter: function (value, options, row) {
                    if (value == 'factory') {
                        return '工厂';
                    } else if (value == 'shop') {
                        return '商家';
                    }
                    return '';
                }
            },
            {
                label: '操作', name: 'operation', width: 50,align:'center',
                formatter: function (value, options, row) {
                    var html = '<li class="dropdown" style="list-style: none;position: absolute;width: 60px;"><a href="#" style="margin:0 auto;" class="dropdown-toggle" style="" data-toggle="dropdown">操作<b class="caret"></b></a>';
                    html += '<ul class="dropdown-menu"  style="min-width:100%;font-size: 12px;">';
                    var options = [];
                    options.push('<li><a href="javascript:;" onclick="return info(' + row.templateId+');">详细</a></li><li class="divider"></li>');
                    html += options.join("")
                    html += '</ul></li>';
                    return html;
                }
            }
        ],
        viewrecords: true,
        height: 600,
        rowNum: 20,
        rowList: [20, 30, 50],
        rownumbers: true,
        rownumWidth: 35,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount",
            userdata: "userData"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"

        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
            var userData = $("#jqGrid").jqGrid('getGridParam', 'userData');
            vm.jsonArray = userData;
        }
    });
    //城市选择展开子城市
    $("#area_select_dialog").on("click", ".show_sub_icon", function (e) {
        $(this).addClass("hide_sub_icon")
        $(this).removeClass("el-icon-circle-plus")
        $(this).addClass("el-icon-remove")
        $(this).parent().parent().find(".sub_scope_list").attr("style", "display: block;");
    });
    //城市选择关闭子城市
    $("#area_select_dialog").on("click", ".hide_sub_icon", function (e) {
        $(this).removeClass("hide_sub_icon")
        $(this).removeClass("el-icon-remove")
        $(this).addClass("el-icon-circle-plus")
        $(this).parent().parent().find(".sub_scope_list").attr("style", "display: none;");
    });
    //给被选中的子级城市添加被选中样式
    $("#area_select_dialog").on("click", ".jsLevel2", function (e) {
        $(this).toggleClass("select");
    });
    //给被选中的父级城市添加被选中样式
    $("#area_select_dialog").on("click", ".jsLevel1", function (e) {
        $(this).toggleClass("select");
    });
    //确定取消按钮
    $("#area_select_dialog").on("click", ".js_btn", function (e) {
        var index=$(this).attr("data-index");
        console.info(index)
        //判断是点击取消还是确认
        if(index == "0"){
            var selected = $(".select")
            if (selected.length > 0) {
                var cityNames = "";
                var cityIds = "";
                $.each(selected,function(){
                    var cityName = $(this).find("span").html();
                    var cityId = $(this).parent().find(".cityId").html();
                    cityIds = cityIds +"," + cityId;
                    cityNames = cityNames + "," + cityName;
                });
                //判断是免邮还是计价
                if(vm.mark == 'valuationWay'){
                    vm.freightAreaList[vm.sum].areaNames = cityNames;
                    vm.freightAreaList[vm.sum].areaIds = cityIds;
                }else{
                    vm.freightAreaList2[vm.sum].areaNames = cityNames;
                    vm.freightAreaList2[vm.sum].areaIds = cityIds;
                }

            }
        }
        $("#area_select_dialog").modal('hide');
    });

    $(function () {
        $('#area_select_dialog').on('hidden.bs.modal', function () {
            debugger;
            $(".isArea").removeClass("isArea");
            $(".select").removeClass("select");
            $(".show_sub_icon").removeClass("hide_sub_icon");
            $(".show_sub_icon").addClass("el-icon-circle-plus");
            $(".show_sub_icon").removeClass("el-icon-remove")
            $(".show_sub_icon").parent().parent().find(".sub_scope_list").attr("style", "display: none;");
        });
    });
});
//运费模板查看详情
function info(templateId){
    vm.getInfo(templateId,false);
    layer.open({
        type: 1,
        skin: 'layui-layer-molv',
        title: "运费模板详细",
        area: ['900px', '400px'],
        shadeClose: false,
        content: jQuery("#freightLayer"),
        btn: [],
    });
}
var vm = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        title: null,
        freightTemplateList:[],
        freightTemplate: {},
        freightAreaList:[],
        freightAreaList2:[],
        jsonArray : {},
        mark: '',
        sum : "",
        sum2 : "",
        q:{
            templateName: ''
        },
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function(){
            vm.showList = false;
            vm.title = "新增";
            vm.freightTemplate = {'freeShipping':'0','valuationWay':'unit','disabled':'0','defTemplate':'0','templateType':'sku','providerType':'shop'};
            vm.freightAreaList = [];
            vm.freightAreaList2 = [];
        },

        //添加城市
        addCity: function(){
            this.freightAreaList.push({'areaNames':'','areaIds':'','rule':'valuationWay'});
            console.info(vm.freightAreaList)
        },
        showCity: function(index){
            vm.mark = 'valuationWay';
            vm.sum = index;
            $("#area_select_dialog").modal("show");

        },
        delCity: function(index){
            vm.freightAreaList.splice(index,1);
        },
        //设置免邮地区
        addFreeArea: function(){
            this.freightAreaList2.push({'areaNames':'','areaIds':'','rule':'freeShipping','firstPrice':'0','continueUnit':'0','continuePrice':'0'});
            console.info(vm.freightAreaList2)
        },
        showFreeArea: function(index){
            vm.mark = 'freeShipping';
            vm.sum = index;
            $("#area_select_dialog").modal("show");
        },
        delFreeArea: function(index){
            vm.freightAreaList2.splice(index,1);
        },
        update: function (event) {
            var templateId = getSelectedRow();
            if(templateId == null){
                return ;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.getInfo(templateId,true)
        },
        saveOrUpdate: function (event) {
            vm.freightTemplate.freightAreaList = vm.freightAreaList;
            vm.freightTemplate.freightAreaList = vm.freightTemplate.freightAreaList.concat(vm.freightAreaList2)
            if(vm.validator()){
                return ;
            }
            var url = vm.freightTemplate.templateId == null ? "freightages/freighttemplate/save" : "freightages/freighttemplate/update";
            $.ajax({
            	type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data:JSON.stringify(vm.freightTemplate),
                success: function(r){
                	if(r.code === 0){
            			alert('操作成功', function(index){
            				vm.reload();
            			});
            		}else{
            			alert(r.msg);
            		}
            	}
            });
        },
        del: function (event) {
            var templateIds = getSelectedRows();
            if(templateIds == null){
                return ;
            }
            var nos=[];
            $.each(templateIds, function(i,val){
                //遍历templateIds获取当前选中的一行的字段
                var rowData = $("#jqGrid").jqGrid('getRowData',val);
                //根据一行字段的对象获得其中的属性
                console.info(rowData)
                nos.push(rowData.templateId)
            });
            confirm('确定要删除选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "freightages/freighttemplate/delete",
                    contentType: "application/json",
                    data: JSON.stringify(nos),
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(index){
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function(templateId,boolean){
            $.get(baseURL + "freightages/freighttemplate/info/"+templateId, function(r){
                vm.freightTemplate = r.freightTemplate;
                vm.freightAreaList =  r.freightAreaList;
                //取出免邮集合
                if(boolean){
                    for(var i = 0;i<vm.freightAreaList.length;i++){
                        if(vm.freightAreaList[i].rule == 'freeShipping'){
                            vm.freightAreaList2.push(vm.freightAreaList[i]);
                            vm.freightAreaList.splice(i,1);
                            i--;
                        }
                    }
                }
            });
        },
        reset: function () {
            vm.q.templateName = '';
        },
        reload: function (event) {
            vm.showList = true;
            vm.freightTemplate = {};
            vm.freightAreaList = [];
            vm.freightAreaList2 = [];
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                page:page,
                postData:{
                    'templateName': vm.q.templateName,
                }
            }).trigger("reloadGrid");
        },
        validator: function () {
            console.log(vm.freightTemplate);
            // console.log(vm.freightAreaList);
            // console.log(vm.freightAreaList2);
            if(isBlank(vm.freightTemplate.templateName)){
                alert("运费模板名不能为空!");
                return true;
            }
            //运费模板数字校验
            var check = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/;
            if(!(check.test(vm.freightTemplate.firstUnit)&&check.test(vm.freightTemplate.firstPrice)&&check.test(vm.freightTemplate.continueUnit)&&check.test(vm.freightTemplate.continuePrice))){
                alert("模板参数只能是正数!")
                return true;
            }
            //校验子表数据
            var freightAreaList = vm.freightTemplate.freightAreaList;
            for(var i = 0;i<freightAreaList.length;i++){
                if(!(check.test(freightAreaList[i].firstUnit)&&check.test(freightAreaList[i].firstPrice)&&check.test(freightAreaList[i].continueUnit)&&check.test(freightAreaList[i].continuePrice))){
                    alert("模板参数只能是正数!")
                    return true;
                }
                if(isBlank(freightAreaList[i].areaNames)){
                    alert("地区不能为空!")
                    return true;
                }
            }
        }
    }
});